<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rust_Dynamic_Layer</title>
    <link rel="stylesheet" href="./leaflet/leaflet.css" />
    <link rel="stylesheet" href="./leaflet/leaflet.draw.css" />

    <link rel="stylesheet" href="./index.css">
    <script src="./leaflet/leaflet.js"></script>
    <script type="text/javascript" src="./leaflet/leaflet.draw.js"></script>
</head>

<body>
    <div id="map"></div>
    <div class="inputBox">
        <textarea name="stylebox" class="stylebox" id="stylebox" placeholder="输入样式定义json"></textarea>
        <div class="btnBox">
            <button onclick="init()">init</button>
            <button onclick="removeRect()">清除绘制</button>
            <button onclick="applyStyle()">应用样式</button>
            <button onclick="zoomToRect()">ZoomTo</button>
        </div>
    </div>
</body>
<script>
    const state = {
        rectLayerId: null,
        pxBounds: null,
        bounds: null,
        imgLayer: null,
        styleStr: null,
    }

    function initMap() {
        const tiandituToken = '517de1f8c853bcfe2ed55a22faad593b	';
        const imgwUrl = 'http://t0.tianditu.gov.cn/vec_w/wmts?' +
            'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&' +
            'TILEMATRIXSET=w&FORMAT=tiles&' +
            'TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=' +
            tiandituToken;
        // const map = L.map('map').setView([39.9, 116.4], 10);
        const map = L.map('map').setView([
            35.6198943413675,
            114.65160314642299,
        ], 7);
        L.tileLayer(imgwUrl, {
            maxZoom: 19,
        }).addTo(map);

        return map;
    }

    function initDraw(map) {
        const drawnItems = new L.FeatureGroup();
        map.addLayer(drawnItems);
        //添加绘制控件
        const drawControl = new L.Control.Draw({
            draw: {
                polyline: false,
                //绘制多边形
                polygon: false,
                //绘制矩形
                rectangle: true,
                //绘制圆
                circle: false,
                //绘制标注
                marker: false,
                //绘制圆形标注
                circlemarker: false
            },
        });
        map.addControl(drawControl);
        return drawnItems;
    }

    async function initLayer() {
        const defaultBounds = L.latLngBounds([[35.21, 113.67,], [35.95, 114.88,]]);
        const initUrl = 'http://localhost:18083/img_init';
        const initParams = {
            param: state.styleStr || 'random',
            w: 1000,
            h: 1000,
            xmin: 111.4,
            ymin: 28,
            xmax: 116.8,
            ymax: 37.1,
        };
        const paramStr = Object.keys(initParams).map(key => `${key}=${initParams[key]}`).join('&');

        const imgBlob = await fetch(
            initUrl,
            {
                method: 'POST',
                body: paramStr,
                mode: 'cors',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            }
        )
            .then(res => res.blob());
        const url = URL.createObjectURL(imgBlob);
        const layer = L.imageOverlay(url, defaultBounds).addTo(map);
        state.imgLayer = layer
        map.fitBounds(defaultBounds)
    }

    const map = initMap();
    initLayer(map);
    const drawnItems = initDraw(map);

    map.on(L.Draw.Event.CREATED, function (e) {
        const drawlayer = e.layer;
        drawnItems.addLayer(drawlayer);
        state.rectLayerId = drawlayer._leaflet_id;
        state.pxBounds = drawlayer._pxBounds;
        state.bounds = drawlayer.getBounds();
    });

    function removeRect() {
        if (state.rectLayerId) {
            drawnItems.removeLayer(state.rectLayerId);
            state.rectLayerId = null;
            // state.bounds = null;
            // state.pxBounds = null;
        }
    }

    async function zoomToRect() {
        if (!state.bounds) {
            return;
        }
        state.imgLayer && map.removeLayer(state.imgLayer)
        const w = state.pxBounds.max.x - state.pxBounds.min.x;
        const h = state.pxBounds.max.y - state.pxBounds.min.y;
        const xmin = state.bounds._southWest.lng;
        const ymin = state.bounds._southWest.lat;
        const xmax = state.bounds._northEast.lng;
        const ymax = state.bounds._northEast.lat;
        const styleStr = state.styleStr;

        const params = {
            param: styleStr || 'random',
            w: 1000,
            h: Math.floor(1000 * h / w),
            xmin,
            ymin,
            xmax,
            ymax,
        };
        const paramStr = Object.keys(params).map(key => `${key}=${params[key]}`).join('&');

        const imgBlob = await fetch(
            'http://localhost:18083/img',
            {
                method: 'POST',
                body: paramStr,
                mode: 'cors',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            }
        )
            .then(res => res.blob());
        const imageUrl = URL.createObjectURL(imgBlob);
        const imageBounds = state.bounds;
        const layer = L.imageOverlay(imageUrl, imageBounds).addTo(map);
        state.imgLayer = layer;
        map.fitBounds(state.bounds);
        removeRect();
    }

    function applyStyle() {
        state.styleStr = document.getElementById('stylebox').value || 'random';
        zoomToRect();
    }

    function init() {
        state.imgLayer && map.removeLayer(state.imgLayer)
        initLayer(map);
    }

</script>

</html>